<template>
  <el-dialog
    v-if="currentStatus === 'allocation'"
    v-model="dialogFormVisible"
    title="分配"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="资产名称">
        <span>{{ form.name }}</span>
      </el-form-item>
      <el-form-item label="分配部门" prop="deptIds" required>
        <el-cascader
          v-model="form.deptIds"
          placeholder="请选择被分配部门"
          :options="deptList"
          :props="{ label: 'label', value: 'value', checkStrictly: true }"
          filterable
          @change="deptChange"
        />
      </el-form-item>
      <el-form-item
        v-show="form.deptIds && form.deptIds.length > 0"
        label="分配人"
      >
        <el-select v-model="form.useUserId" value-key="id">
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          maxlength="250"
          placeholder="请输入备注"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
  <el-dialog
    v-if="currentStatus === 'report'"
    v-model="dialogFormVisible"
    title="报备"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="资产名称">
        <span>{{ form.name }}</span>
      </el-form-item>
      <el-form-item label="报备类型" prop="checkType" required>
        <el-select
          v-model="form.checkType"
          clearable
          placeholder="请选择报备类型"
        >
          <el-option
            v-for="item in dictData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报备金额" prop="fee" required>
        <el-input v-model="form.fee" placeholder="请输入报备金额" />
      </el-form-item>
      <el-form-item label="上传图片" prop="imgUrl">
        <el-upload
          :action="action"
          list-type="picture-card"
          :headers="headers"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :on-preview="handlePictureCardPreview"
          :show-file-list="false"
          limit="1"
        >
          <el-icon v-if="!form.imgUrl">
            <Plus />
          </el-icon>
          <img
            v-if="form.imgUrl"
            :src="form.imgUrl"
            alt=""
            style="width: 148px; height: 148px"
          />
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="form.imgUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          maxlength="250"
          placeholder="请输入备注"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="openDictionary">报备类型配置</el-button>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
  <el-dialog
    v-if="currentStatus === 'damage'"
    v-model="dialogFormVisible"
    title="报损"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="100px" :model="form">
      <el-form-item label="资产名称">
        <span>{{ form.name }}</span>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          maxlength="250"
          placeholder="请输入备注"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
  <dictionary
    ref="dictionaryRef"
    :dict-list-data="DictList"
    @fetch-data="fetchDictListState"
  />
</template>

<script>
  import { getDeptTreeList } from '@/api/departmentManagement'
  import { getList as fetchUserList } from '@/api/userManagement'
  import { assetChange } from '@/api/assetManagement'
  import { useUserStore } from '@/store/modules/user'
  import { baseURL } from '@/config'
  import {
    fetchDictList,
    fetchDictSelectList,
  } from '@/api/dictionaryManagement'
  export default defineComponent({
    name: 'AssetManagementAssign',
    components: {
      Dictionary: defineAsyncComponent(() =>
        import('@/components/biz/dictionaryPopup')
      ),
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const userStore = useUserStore()
      const { token } = storeToRefs(userStore)
      const state = reactive({
        dictionaryRef: null,
        deptList: [],
        userList: [],
        headers: {},
        action: '',
        formRef: null,
        DictList: [],
        treeData: [],
        defaultNum: 0,
        dictData: [],
        statusList: [
          {
            label: '报备',
            value: 0,
          },
          {
            label: '报销',
            value: 1,
          },
          {
            label: '加油',
            value: 2,
          },
        ],
        defaultProps: {
          children: 'children',
          label: 'title',
        },
        form: {},
        rules: {
          deptIds: [
            { required: true, trigger: 'blur', message: '请选择分配部门' },
          ],
          checkType: [
            { required: true, trigger: 'blur', message: '请选择报备部门' },
          ],
          fee: [{ required: true, trigger: 'blur', message: '请输入报备金额' }],
        },
        currentStatus: '', //damage 报损 report 报备 allocation 分配
        dialogFormVisible: false,
      })
      const dialogImageUrl = ref('')
      const dialogVisible = ref(false)
      const handleRemove = (uploadFile, uploadFiles) => {
        console.log(uploadFiles.response)
      }
      const handleSuccess = (uploadFile) => {
        state.form.imgUrl = uploadFile.data.url
      }
      const handlePictureCardPreview = (uploadFile) => {
        dialogImageUrl.value = uploadFile.url
        dialogVisible.value = true
      }
      const fetchDictListState = async () => {
        state.listLoading = true
        try {
          const params = {
            keywords: '',
            typeCode: 'assetCheckType',
            pageNum: 1,
            pageSize: 999,
          }
          const {
            data: { list },
          } = await fetchDictList(params)
          state.DictList = list
          state.listLoading = false
          // 当增加字典或修改删除操作时,调取字典下拉数据
          fetchDictLists()
        } catch (e) {
          console.log(e)
        }
      }
      const openDictionary = () => {
        try {
          state.dictionaryRef.showEdit(state.DictList)
        } catch (e) {
          console.log(e)
        }
      }
      const showEdit = (row, currentStatus) => {
        try {
          getDeptList()
          if (row) {
            const form = JSON.parse(JSON.stringify(row))
            state.form.id = form.id
            state.form.name = form.name
            state.form.useUserId = form.useUserId
            state.form.remark = form.remark
            state.currentStatus = currentStatus
            state.dialogFormVisible = true
          }
        } catch (e) {
          console.log(e)
        }
      }

      const getDeptList = async () => {
        try {
          const { data } = await getDeptTreeList({})
          state.deptList = data
        } catch (e) {
          console.log(e)
        }
      }

      const deptChange = (deptId) => {
        if (deptId && deptId.length > 0) {
          getUserList({
            pageNum: 1,
            pageSize: 999,
            deptId: deptId[deptId.length - 1],
          })
        }
      }

      const getUserList = async (params) => {
        state.userList = []
        try {
          const { data } = await fetchUserList(params)
          state.userList = data.list || []
        } catch (e) {
          console.error(e)
        }
      }

      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            // currentStatus: '', //damage 1 报损 report 2 报备 allocation 0 分配
            let params = {}
            if (state.currentStatus === 'allocation') {
              const deptId = state.form.deptIds[state.form.deptIds.length - 1]
              params = {
                id: state.form.id,
                type: 0,
                deptId: deptId,
                remark: state.form.remark || '',
                useUserId: state.form.useUserId || null,
              }
            }
            if (state.currentStatus === 'report') {
              params = {
                id: state.form.id,
                type: 2,
                remark: state.form.remark || '',
                imgUrl: state.form.imgUrl,
                checkType: state.form.checkType,
                fee: state.form.fee,
              }
            }
            if (state.currentStatus === 'damage') {
              params = {
                id: state.form.id,
                type: 1,
                remark: state.form.remark || '',
              }
            }
            const arr = []
            arr.push(params)
            try {
              const { code, msg } = await assetChange(arr)
              if (code === '1') {
                $baseMessage(msg, 'success', 'vab-hey-message-success')
                emit('fetch-data')
                close()
              } else {
                $baseMessage(msg, 'error', 'vab-hey-message-error')
              }
            } catch (e) {
              console.log(e)
            }
          }
        })
      }

      /**
       * resetFields()已重置form,不需要再去操作form
       **/
      const close = () => {
        state['formRef'].resetFields()
        // state.form = {
        //   id: '',
        //   name: '',
        //   useUserId: '',
        //   remark: '',
        // }
        state.dialogFormVisible = false
      }
      const fetchDictLists = async () => {
        const typeCode = {
          typeCode: 'assetCheckType',
        }
        const { data } = await fetchDictSelectList(typeCode)
        state.dictData = data
      }

      onMounted(() => {
        fetchDictLists()
        fetchDictListState()
        const tokens = JSON.parse(JSON.stringify(token))
        state.headers['Authorization'] = `Bearer ${tokens._object.token}`
        state.action = `${baseURL}/zgyp-system/api/v1/files`
      })
      return {
        ...toRefs(state),
        deptChange,
        showEdit,
        handleRemove,
        handleSuccess,
        handlePictureCardPreview,
        save,
        close,
        openDictionary,
        fetchDictListState,
      }
    },
  })
</script>
<style scoped>
  .tree-container {
    width: 100%;
    min-height: 200px;
    border: 1px solid #dcdfe6;
  }
</style>
